<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller
{
    /** @var \User */
    private $CurrentUser;

    public function __construct()
    {
        parent::__construct();

        // 检查状态
        YimeDevTools::checkSiteStatus();

        if ($this->router->fetch_method() !== 'weibologin') {
            //去除微博绑定确认session
            $this->session->unset_userdata('bindType');
        }

        $SiteName = Option_Model::getOption('site_name');
        $this->CurrentUser = UserManager::getCurrentUserBySession();
        $CommodityCategoryArray = CommodityCategory_Model::getCommodityCategoryArray();
        $PlusOneTop10CommodityArray = YimeTools::getPlusOneTop10CommodityArray();
        $LatestReleaseTop10CommodityArray = YimeTools::getLatestReleaseTop10CommodityArray();

        $this->load->vars(array(
            'SiteName' => $SiteName,
            'CurrentUser' => $this->CurrentUser,
            'CommodityCategoryArray' => $CommodityCategoryArray,
            'PlusOneTop10CommodityArray' => $PlusOneTop10CommodityArray,
            'LatestReleaseTop10CommodityArray' => $LatestReleaseTop10CommodityArray,
            'NewMsgCount' => UserNewMsg_Model::getUserNewMsgByUserId($this->CurrentUser->getId())->getNewMsgCount(),
            'HeaderJs' => array(
                base_url('public/js/libraries/HtmlBuilder.js'),
                base_url('public/js/libraries/CommodityComment.js'),
                base_url('public/js/libraries/CommodityCommentSet.js'),
                base_url('public/js/libraries/CommodityRequireComment.js'),
                base_url('public/js/libraries/CommodityRequireCommentSet.js'),
            ),
        ));
    }

    public function index($offset = 0)
    {
        if ($this->input->cookie('visited', TRUE) == false && $this->CurrentUser->getId() == 0) {
            //echo "这是引导页引导页引导页,<a href='".base_url('/home/skip_userguide')."'>点我跳过</a>,要看到我请清除COOKIES";
            //微博接口
            if($this->getrobot()){
                redirect(base_url('home/skip_userguide'));
            }
            $o = SaeTOAuthV2::Init(WB_AKEY, WB_SKEY);
            $code_url = $o->getAuthorizeURL(WB_CALLBACK_URL);

            $this->load->helper('captcha');
            $data = array(
                'word' => random_string('alnum', 4),
                'img_path' => './public/captcha/',
                'img_url' => base_url('public/captcha') . '/',
                'font_path' => './public/font/arialbd.ttf',
                'img_width' => 160,
                'img_height' => 43,
            );
            $captcha = create_captcha($data);
            try {
                Captcha_Model::update($captcha);
            } catch (Exception $ex) {
                $captcha = array('image' => '<p class="text-danger text-center" style="line-height: 40px;background: #fc8;">验证码生成出错</p>');
            }

            $this->load->view('home/guide', array(
                'captcha' => $captcha,
                'weibologin' => $code_url,
            ));
            return;
        }

        if (!is_numeric($offset) && $offset < 0) $offset = 0;
        $prePage = 10;

        $CommodityArray = Commodity_Model::getCommodityArray($prePage, $offset, 'release_time');

        $paginationConfig['base_url'] = base_url('home/index');
        $paginationConfig['total_rows'] = Commodity_Model::countCommodity();
        $paginationConfig['per_page'] = $prePage;
        $paginationConfig['uri_segment'] = '3';
        $this->pagination->initialize($paginationConfig);

        $this->load->vars(array(
            'CommodityArray' => $CommodityArray,
            'NowOffset' => $offset,
            'Pagination' => $this->pagination->create_links(),
        ));
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/homepage');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function skip_userguide()
    {
        $this->input->set_cookie('visited', 1, 15552000); //180天有效
        redirect(base_url());
    }

    //判断搜索引擎入口访问，SEO优化
    public function getrobot() {
        if (empty($_SERVER['HTTP_USER_AGENT']))
        {
            return false;
        }

        $searchEngineBot = array(
            'googlebot'=>'google',
            'mediapartners-google'=>'google',
            'baiduspider'=>'baidu',
            'msnbot'=>'msn',
            'yodaobot'=>'yodao',
            'youdaobot'=>'yodao',
            'yahoo! slurp'=>'yahoo',
            'yahoo! slurp china'=>'yahoo',
            'iaskspider'=>'iask',
            'sogou web spider'=>'sogou',
            'sogou push spider'=>'sogou',
            'sosospider'=>'soso',
            'spider'=>'other',
            'crawler'=>'other',
        );
        $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach ($searchEngineBot as $key => $value)
        {
            if (strpos($spider, $key)!== false)
            {
                return true;
            }
        }
        return false;
    }

    public function searchCommodity()
    {
        $searchStr = $this->input->get_post('search-str');
        if (!($searchStr)) redirect(base_url());

        $offset = $this->input->get_post('page');
        if (!is_numeric($offset) && $offset < 0) $offset = 0;
        $prePage = 10;

        $CommodityArray = Commodity_Model::getCommodityArrayBySearchString($searchStr, $prePage, $offset, 'release_time');

        $paginationConfig['base_url'] = base_url('home/searchCommodity?search-str=' . $searchStr);
        $paginationConfig['total_rows'] = Commodity_Model::countCommodityBySearchString($searchStr);
        $paginationConfig['per_page'] = $prePage;
        $paginationConfig['page_query_string'] = TRUE;
        $paginationConfig['query_string_segment'] = 'page';
        $this->pagination->initialize($paginationConfig);

        $this->load->vars(array(
            'CommodityArray' => $CommodityArray,
            'NowOffset' => $offset,
            'Pagination' => $this->pagination->create_links(),
        ));
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/search-commodity');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function details($commodityId = 0)
    {
        if (!is_numeric($commodityId) && $commodityId < 0)
            redirect(base_url());

        $thatCommodity = Commodity_Model::getCommodityById($commodityId);

        $this->load->vars(array(
            'thatCommodity' => $thatCommodity,
            'SiteName'      => '易米网《'.$thatCommodity->getTitle().'》',
        ));

        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/details');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function category($commodityCatId = 0, $offset = 0)
    {
        if (!is_numeric($commodityCatId) || $commodityCatId < 0) redirect(base_url());
        if (!is_numeric($offset) || $offset < 0) $offset = 0;
        $prePage = 10;

        $array = CommodityCategory_Model::getDescendantCommodityCategoryIdArrayById($commodityCatId);
        $array[] = $commodityCatId;

        $CommodityArray = Commodity_Model::getDescendantCommodityArrayByCommodityCatIdArray($array, 10, $offset, 'release_time');
        $NowCategory = CommodityCategory_Model::getCommodityCategoryById($commodityCatId);

        $paginationConfig['base_url'] = base_url('home/category/' . $commodityCatId);
        $paginationConfig['total_rows'] = Commodity_Model::countCommodityByCommodityCategoryIdArray($array);
        $paginationConfig['per_page'] = $prePage;
        $paginationConfig['uri_segment'] = '4';
        $this->pagination->initialize($paginationConfig);

        $this->load->vars(array(
            'NowCategoryId' => $commodityCatId,
            'NowMasterCategoryId' => $NowCategory->getMasterCommodityCategoryId(),
            'NowCategoryName' => $NowCategory->getName(),
            'CommodityArray' => $CommodityArray,
            'Pagination' => $this->pagination->create_links(),
        ));

        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/category');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function commodityRequire($releaseType = 0, $offset = 0)
    {

        if (!is_numeric($offset) && $offset < 0) $offset = 0;
        $prePage = 10;
        $paginationConfig['base_url'] = base_url('home/commodityRequire/' . $releaseType);
        if ($releaseType)
            $paginationConfig['total_rows'] = CommodityRequire_Model::countCommodityRequireByReleaseType($releaseType);
        else
            $paginationConfig['total_rows'] = CommodityRequire_Model::countCommodityRequire();
        $paginationConfig['per_page'] = $prePage;
        $paginationConfig['uri_segment'] = '4';
        $this->pagination->initialize($paginationConfig);

        if ($releaseType) {
            $CommodityRequireArray = CommodityRequire_Model::getCommodityRequireArrayByReleaseType($releaseType, $prePage, $offset);
        } else {
            $CommodityRequireArray = CommodityRequire_Model::getCommodityRequireArray($prePage, $offset, 'release_time');
        }

        $this->load->vars(array(
            'CommodityRequireArray' => $CommodityRequireArray,
            'ReleaseType' => $releaseType,
            'offset' => $offset,
            'Pagination' => $this->pagination->create_links(),
            'SiteName'   => '易米网-物品求购',
        ));

        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/commodity-require');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function userCenter($action = false, $userId = 0, $offset = 0)
    {
        //微博接口
        $o = SaeTOAuthV2::Init(WB_AKEY, WB_SKEY);
        $code_url = $o->getAuthorizeURL(WB_CALLBACK_URL);

        if ($userId == 0) $thatUser = $this->CurrentUser;
        else $thatUser = User_Model::getUserById($userId);

        if (!isset($thatUser) || !$thatUser || !($thatUser->getId() > 0))
            redirect(base_url());

        $thatWeiboUserInfo = WeiboInfo_Model::getWeiboByUserId($thatUser->getId());
        $this->load->vars(array(
            'thatUser' => $thatUser,
            'thatWeiboUserInfo' => $thatWeiboUserInfo,
            'weibourl' => $code_url,
        ));

        $this->load->view('home/html-header');
        $this->load->view('home/header');

        $this->load->vars(array('UserCenterAction' => $action));
        switch ($action) {
            case 'commodity':
                if (!is_numeric($offset) && $offset < 0) $offset = 0;
                $prePage = 10;
                $paginationConfig['base_url'] = base_url('home/userCenter/commodity/' . $thatUser->getId());
                $paginationConfig['total_rows'] = Commodity_Model::countCommodityByUserId($thatUser->getId());
                $paginationConfig['per_page'] = $prePage;
                $paginationConfig['uri_segment'] = '5';
                $this->pagination->initialize($paginationConfig);

                $thatCommodityArray = Commodity_Model::getCommodityArrayByUserId($thatUser->getId(), $prePage, $offset, 'release_time');
                $this->load->vars(array(
                    'CommodityArray' => $thatCommodityArray,
                    'Pagination' => $this->pagination->create_links(),
                ));
                $this->load->view('home/user-center/commodity');
                break;
            case 'wantToBuy':
                if (!is_numeric($offset) && $offset < 0) $offset = 0;
                $prePage = 10;
                $paginationConfig['base_url'] = base_url('home/userCenter/wantToBuy/' . $thatUser->getId());
                $paginationConfig['total_rows'] = CommodityRequire_Model::countCommodityRequireByUserId($thatUser->getId());
                $paginationConfig['per_page'] = $prePage;
                $paginationConfig['uri_segment'] = '5';
                $this->pagination->initialize($paginationConfig);

                $thatCommodityRequireArray = CommodityRequire_Model::getCommodityRequireArrayByUserId($thatUser->getId(), $prePage, $offset);

                $this->load->vars(array(
                    'CommodityRequireArray' => $thatCommodityRequireArray,
                    'Pagination' => $this->pagination->create_links(),
                ));
                $this->load->view('home/user-center/require');
                break;
            case 'favorite':
                if (!is_numeric($offset) && $offset < 0) $offset = 0;
                $prePage = 10;
                $paginationConfig['base_url'] = base_url('home/userCenter/favorite/' . $thatUser->getId());
                $paginationConfig['total_rows'] = CommodityFavorite_Model::countCommodityFavoriteByUserId($thatUser->getId());
                $paginationConfig['per_page'] = $prePage;
                $paginationConfig['uri_segment'] = '5';
                $this->pagination->initialize($paginationConfig);

                $thatCommodityFavArray = CommodityFavorite_Model::getCommodityFavArrayByUserId($thatUser->getId(), $prePage, $offset);
                $this->load->vars(array(
                    'CommodityFavArray' => $thatCommodityFavArray,
                    'Pagination' => $this->pagination->create_links(),
                ));
                $this->load->view('home/user-center/fav');
                break;
            case 'userInfo':
                $this->load->view('home/user-center/user-info');
                break;
            case 'message':
                if ($this->CurrentUser->getId() != $thatUser->getId())
                    redirect(base_url());

                $userNewMsg = UserNewMsg_Model::getUserNewMsgByUserId($thatUser->getId());
                $userNewMsg->setNewMsgCount(0);
                $userNewMsg->setNewMsgIdJson(json_encode(array()));
                UserNewMsg_Model::save($userNewMsg);

                if (!is_numeric($offset) && $offset < 0) $offset = 0;
                $prePage = 10;

                $userCommentData = UserComment::getUserCommentDataByToUserIdOrMasterId($thatUser->getId(), $prePage, $offset);

                $comments = isset($userCommentData['comments']) ? $userCommentData['comments'] : null;
                $this->pagination->initialize(array(
                    'base_url' => base_url('home/userCenter/message/' . $thatUser->getId()),
                    'total_rows' => isset($userCommentData['countComments']) ? $userCommentData['countComments'] : UserComment::countUserCommentArrayByToUserIdOrMasterId($thatUser->getId()),
                    'per_page' => $prePage,
                    'uri_segment' => 5,
                ));

                $this->load->vars(array(
                    'comments' => $comments,
                    'commentsPagination' => $this->pagination->create_links(),
                ));
                $this->load->view('home/user-center/message');
                break;
            default:
                $this->load->view('home/user-center/user-info');
                break;
        }
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }


    public function plaza()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/plaza');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function activation($activationCode = false)
    {
        if (!$activationCode) show_404();

        $this->load->vars(array(
            'ActivationCode' => $activationCode,
        ));

        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/activation');
        $this->load->view('home/footer');
        $this->load->view('home/html-footer');
    }

    public function releaseType($releaseType = 0, $offset = 0)
    {
        if (!is_numeric($releaseType) && $releaseType < 0) $releaseType = 0;
        $prePage = 10;
        $CommodityArray = Commodity_Model::getCommodityArrayByReleaseType($releaseType, $prePage, $offset);

        $paginationConfig['base_url'] = base_url('home/releaseType/' . $releaseType);
        $paginationConfig['total_rows'] = Commodity_Model::countCommodityByreleaseType($releaseType);
        $paginationConfig['per_page'] = $prePage;
        $paginationConfig['uri_segment'] = '4';
        $this->pagination->initialize($paginationConfig);

        $this->load->vars(array(
            'CommodityArray' => $CommodityArray,
            'ReleaseType' => $releaseType,
            'NowOffset' => $offset,
            'Pagination' => $this->pagination->create_links(),
        ));
        $page['offset'] = $offset;
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/homepage', $page);
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function aboutus()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/aboutus');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');

    }

    public function weibologin()
    {
        $LoginCheck = WeiboManger::checkWeiboBind();
        $userID = $this->session->userdata('UserID');
        if ($LoginCheck == 'noBind') {
            if ($userID == '' || $userID == 0 || !$userID) {
                $this->load->view('home/html-header');
                $this->load->view('home/header');
                $this->load->view('home/registerstyle');
                $this->load->view('home/footer');
                $this->load->view('home/html-footer');
            } else {
                redirect(base_url('home/binduser'));
            }
        } elseif ($LoginCheck == 'fail') {
            $this->load->view('home/html-header');
            $this->load->view('home/header');
            $this->load->view('home/result-show', array(
                'result_type' => 'error',
                'result_text' => '微博获取出错，请重试',
            ));
            $this->load->view('home/footer');
            $this->load->view('home/html-footer');
        } elseif ($LoginCheck == 'noAllow') {
            $this->load->view('home/html-header');
            $this->load->view('home/header');
            $this->load->view('home/result-show', array(
                'result_type' => 'error',
                'result_text' => '该微博账户已绑定其他易米帐号',
            ));
            $this->load->view('home/footer');
            $this->load->view('home/html-footer');
        } elseif ($LoginCheck == 'login') {
            redirect(base_url());
        }
    }

    public function binduser()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/binduser');
        $this->load->view('home/footer');
        $this->load->view('home/html-footer');
    }

    public function weiboregister()
    {
        $this->load->helper('captcha');
        $data = array(
            'word' => random_string('alnum', 4),
            'img_path' => './public/captcha/',
            'img_url' => base_url('public/captcha') . '/',
            'font_path' => './public/font/arialbd.ttf',
            'img_width' => 160,
            'img_height' => 43,
        );
        $captcha = create_captcha($data);
        try {
            Captcha_Model::update($captcha);
        } catch (Exception $ex) {
            $captcha = array('image' => '<p class="text-danger text-center" style="line-height: 40px;background: #fc8;">验证码生成出错</p>');
        }

        $userWeiboInfo = WeiboManger::getWeiboInfo();
        $this->load->vars(array('weiboUserInfo' => $userWeiboInfo));
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/registerstyle', array('captcha' => $captcha));
        $this->load->view('home/footer');
        $this->load->view('home/html-footer');
    }

    public function privacypolicy()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/privacypolicy');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');

    }

    public function legalnotices()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/legalnotices');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function official()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/official');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function hierarchy()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/hierarchy');
        $this->load->view('home/footer');
        $this->load->view('home/quick-link');
        $this->load->view('home/html-footer');
    }

    public function changeschool($schoolcode = 0)
    {
        if ($schoolcode) {
            $school = School_Model::getSchoolByUnicode($schoolcode);
            if ($school) {
                $this->input->set_cookie('schoolcode', $school->getUnicode(), 15552000); //180天有效
                $this->input->set_cookie('schoolname', $school->getName(), 15552000); //180天有效
                $this->input->set_cookie('schoolid', $school->getId(), 15552000); //180天有效
                $this->input->set_cookie('visited', 1, 15552000); //180天有效
            }
        } else {
            $this->input->set_cookie('schoolcode', 0, 15552000); //180天有效
        }
        redirect(base_url());
    }

    public function result_show()
    {
        $model = $this->input->get('model');
        $result = $this->input->get('result');
        $result = ResultShow::show($model, $result);
        $this->load->vars(array(
            'result_type' => $model,
            'result_text' => $result,
        ));
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/result-show');
        $this->load->view('home/html-footer');
    }

    public function resetpwd()
    {
        $this->load->helper('captcha');
        $data = array(
            'word' => random_string('alnum', 4),
            'img_path' => './public/captcha/',
            'img_url' => base_url('public/captcha') . '/',
            'font_path' => './public/font/arialbd.ttf',
            'img_width' => 160,
            'img_height' => 43,
        );
        $captcha = create_captcha($data);
        try {
            Captcha_Model::update($captcha);
        } catch (Exception $ex) {
            $captcha = array('image' => '<p class="text-danger text-center" style="line-height: 40px;background: #fc8;">验证码生成出错</p>');
        }

        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/resetpwd', array('captcha' => $captcha));
        $this->load->view('home/footer');
        $this->load->view('home/html-footer');
    }

    public function resetpassword($resetpwd_token = '')
    {
        $thatUser = User_Model::getUserById(UserResetPwd_Model::getUserIdByResetPwdToken($resetpwd_token));
        if (!$thatUser) {
            $this->load->vars(array(
                'result' => 'error',
            ));
        } else {
            $salt = sprintf('%05d', rand(0, 99999));
            $thatUser->setSalt($salt);
            User_Model::update($thatUser);
            $this->load->vars(array(
                'result' => 'success',
                'email' => $thatUser->getEmail(),
                'key' => $resetpwd_token,
            ));

        }
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/setnewpwd');
        $this->load->view('home/footer');
        $this->load->view('home/html-footer');

    }

    public function test()
    {
        $this->load->view('home/html-header');
        $this->load->view('home/header');
        $this->load->view('home/schoolauth');
    }
}